<template>
  <div class="container mx-auto px-4 pbBrooklyn-16">
    <!-- 搜索和分类 -->
    <div class="sticky top-0 bg-white py-4 z-10 border-b">
      <div class="flex items-center mb-4">
        <div class="relative flex-1">
          <input 
            v-model="searchQuery"
            type="text" 
            placeholder="搜索商品..." 
            class="w-full p-3 pl-10 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:outline-none transition"
          >
          <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 absolute left-3 top-3.5 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
          </svg>
        </div>
        
        <button 
          ref="cartButtonRef"
          @click="toggleCart"
          class="ml-4 relative p-3 bg-blue-500 text-white rounded-full hover:bg-blue-600 transition shadow-lg cart-box"
          :class="{ 'animate-cart-bounce': cartTrigger }"
        >
          <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z" />
          </svg>
          <span class="absolute -top-1 -right-1 bg-red-500 text-white rounded-full w-5 h-5 flex items-center justify-center text-xs shadow-md">
            {{ totalItems }}
          </span>
        </button>
      </div>

      <div class="flex flex-wrap gap-2">
        <button 
          v-for="category in categories" 
          :key="category"
          @click="selectCategory(category)"
          class="px-4 py-2 rounded-full text-sm font-medium transition shadow-sm"
          :class="{
            'bg-blue-500 text-white shadow-md': selectedCategory === category,
            'bg-gray-100 text-gray-700 hover:bg-gray-200': selectedCategory !== category
          }"
        >
          {{ category }}
        </button>
      </div>
    </div>

    <!-- 商品瀑布流 -->
    <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4 mt-4">
      <div 
        v-for="(product, index) in filteredProducts"
        :key="product.id"
        ref="productCardRefs"
        class="bg-white rounded-xl overflow-hidden shadow-md hover:shadow-lg transition cursor-pointer group"
        :class="{ 'opacity-80': animatingItems.includes(product.id) }"
        @click="handleProductClick($event, product, index)"
      >
        <div class="relative overflow-hidden">
          <img 
            :src="product.image" 
            alt="" 
            class="w-full h-48 object-cover transform group-hover:scale-105 transition duration-500"
          >
          <!-- <div 
            v-if="animatingItems.includes(product.id)"
            class="absolute inset-0 bg-blue-500 bg-opacity-50 flex items-center justify-center"
          >
            <svg xmlns="http://www.w3.org/2000/svg" class="h-12 w-12 text-white animate-spin" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
            </svg>
          </div> -->
        </div>
        <div class="p-4">
          <h3 class="font-bold text-gray-800 mb-1">{{ product.name }}</h3>
          <p class="text-gray-600 text-sm mb-2 line-clamp-2">{{ product.description }}</p>
          <div class="flex justify-between items-center">
            <span class="text-red-500 font-bold">¥{{ product.price }}</span>
            <button class="text-blue-500 hover:text-blue-700 transition">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v3m0 0v3m0-3h3m-3 0H9m12 0a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 动画元素 -->
    <AddToCartAnim 
      v-if="showAnim" 
      :startPos="animStartPos" 
      :endPos="animEndPos" 
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { mockProducts, categories, type Product } from '../data/mockProducts';
import { useCart } from '../composables/useCart';
import AddToCartAnim from './AddToCartAnim.vue';

// 购物车逻辑
const { addToCart, cartTrigger, totalItems, toggleCart, animatingItems } = useCart();

// 商品数据
const products = ref(mockProducts);
const searchQuery = ref('');
const selectedCategory = ref('全部');

// 瀑布流相关
const productCardRefs = ref<HTMLElement[]>([]);
const showAnim = ref(false);
const animStartPos = ref({ x: 0, y: 0 });
const animEndPos = ref({ x: 0, y: 0 });
 // 添加购物车按钮的引用
const cartButtonRef = ref<HTMLElement | null>(null);

// 获取购物车位置（实际项目中应该获取购物车按钮位置）
const getCartPosition = (): { x: number; y: number } => {
  if (typeof window === 'undefined' || !cartButtonRef.value) {
    return { x: 0, y: 0 };
  }
  
  try {
    const rect = cartButtonRef.value.getBoundingClientRect();
    return {
      x: rect.left + rect.width / 2,
      y: rect.top + rect.height / 2
    };
  } catch (e) {
    console.error("获取购物车按钮位置失败:", e);
    return { x: window.innerWidth - 50, y: 50 }; // 备用位置
  }
};

// 处理商品点击
const handleProductClick = (event: MouseEvent, product: Product, index: number) => {
  const cardElement = productCardRefs.value[index];
  if (cardElement) {
    const rect = cardElement.getBoundingClientRect();
    animStartPos.value = {
      x: rect.left + rect.width / 2,
      y: rect.top + rect.height / 2
    };
    animEndPos.value = getCartPosition();
    showAnim.value = true;
    
    // 添加购物车
    addToCart(product);
    
    // 500ms后隐藏动画
    setTimeout(() => {
      showAnim.value = false;
    }, 1000);
  }
};

// 分类筛选
const selectCategory = (category: string) => {
  selectedCategory.value = category;
};

// 过滤商品
const filteredProducts = computed(() => {
  let result = [...products.value];
  
  // 分类筛选
  if (selectedCategory.value !== '全部') {
    result = result.filter(p => p.category === selectedCategory.value);
  }
  
  // 搜索筛选
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    result = result.filter(p => 
      p.name.toLowerCase().includes(query) || 
      p.description.toLowerCase().includes(query)
    );
  }
  
  return result;
});
</script>